/*
 * Copyright (c) 2001 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.ui;

import java.util.ArrayList;
import java.util.List;

import net.sourceforge.perforce.core.resources.LocalFile;
import net.sourceforge.perforce.core.resources.LocalFolder;
import net.sourceforge.perforce.core.resources.LocalResource;
import org.eclipse.compare.ResourceNode;
import org.eclipse.compare.structuremergeviewer.IStructureComparator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.team.core.TeamException;

/**
  * @version 	1.0
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class PerforceResourceNode extends ResourceNode
{
	private List children;
	
	/**
	 * Constructor for PerforceResourceNode.
	 * @param resource
	 */
	public PerforceResourceNode(IResource resource)
	{
		super(resource);
	}
	
	/*
	 * @see IStructureComparator#getChildren()
	 */
	public Object[] getChildren()
	{
		if (children == null)
		{
			children = new ArrayList();
			
			IResource resource = getResource();
			if (resource instanceof IContainer)
			{
				try
				{
					LocalFolder localFolder = (LocalFolder)LocalResource.createFromResource(resource);
					
					LocalFile[] files = localFolder.getFiles();
					for (int i = 0, length = files.length; i < length; i++) 
					{
						IResource child = files[i].toResource();
						if (child.exists()) 
						{
							IStructureComparator childNode = createChild(child);
							if (childNode != null) 
								children.add(childNode);
						}
					}	
									
					LocalFolder[] folders = localFolder.getFolders();
					for (int i = 0, length = folders.length; i < length; i++) 
					{
						IResource child = folders[i].toResource();
						if (child.exists()) 
						{
							IStructureComparator childNode = createChild(child);
							if (childNode != null) 
								children.add(childNode);
						}
					}	
				}
				catch (TeamException e)
				{
					PerforceUIPlugin.log(e.getStatus());
				}
			}
		}
		
		return children.toArray();
	}

	protected IStructureComparator createChild(IResource child) 
	{
		return new PerforceResourceNode(child);
	}
}
